package geo

// In alghoritm @see http://alienryderflex.com/polygon/
func (point *Point) In(polygon *Polygon) bool {
	var prev int
	result := false

	for k, p := range polygon.Coordinates {
		if k <= 0 {
			prev = len(polygon.Coordinates) - 1
		} else {
			prev = k - 1
		}

		iflng := p.Lng < point.Lng && polygon.Coordinates[prev].Lng >= point.Lng || polygon.Coordinates[prev].Lng < point.Lng && p.Lng >= point.Lng
		iflat := p.Lat <= point.Lat || polygon.Coordinates[prev].Lat <= point.Lat

		if iflng && iflat {
			if p.Lat+(point.Lng-p.Lng)/(polygon.Coordinates[prev].Lng-p.Lng)*(polygon.Coordinates[prev].Lat-p.Lat) < point.Lat {
				result = !result
			}
		}

		polygon.Itterations++
	}

	return result
}
